package avicit.bdp.dds.api.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.dds.dispatch.enums.ExecutionStatus;
import avicit.bdp.dds.api.dto.StateDto;
import avicit.bdp.dds.dao.entity.DataStat;
import avicit.bdp.dds.dao.entity.Project;
import avicit.bdp.dds.dao.mapper.StateMapper;
import avicit.platform6.core.context.ThreadContextHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author felix
 * project service
 **/
@Service
public class DataStatService extends BaseService<StateMapper, DataStat> {

    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private ProjectService projectService;

    /**
     * 获取历史成功数
     *
     */
    public Integer getSuccessHistoryCount(String projectId) {
        return this.mapper.getSuccessHistoryCount(projectId);
    }

    /**
     * 获取历史失败数
     *
     * @return
     */
    public Integer getFailHistoryCount(String projectId) {
        return this.mapper.getFailHistoryCount(projectId);
    }

    /**
     * 折线图
     *
     * @param projectId 项目空间ID
     * @return
     */
    public Map<String, Object> getProcessLine(String projectId) {
        //返回map
        Map<String, Object> map = Maps.newHashMap();
        //数据list
        List<Map<String, Object>> dataList = Lists.newArrayList();
        //x轴list
        List<String> timeList = Lists.newArrayList();
        String yesterday = DateUtils.getDayNumBeforeToday(1);
        String today = DateUtils.getSystemCurrentDate();
        //昨日和平均历史数据
        List<DataStat> statList;
        //今日数据集合
        List<String> todayList = Lists.newArrayList();
        //昨日数据集合
        List<String> yesterdayList = Lists.newArrayList();
        //历史平均数据集合
        List<String> historyAvgList = Lists.newArrayList();
        //数据Map
        Map<String, Object> yesterdayDataMap = Maps.newHashMap();

        if (StringUtils.isBlank(projectId)) {
            //项目空间id集合
            List<String> projectIdList = Lists.newArrayList();
            String userId = ThreadContextHelper.getUserId();
            if (StringUtils.isBlank(userId)) {
                userId = "1";
            }
            List<Project> list = projectService.getProjectByUserId(userId);
            for (Project project : list) {
                projectIdList.add(project.getId());
            }
            statList = this.mapper.getAllData(yesterday, projectIdList);
        } else {
            statList = this.mapper.getDataByProjectId(yesterday, projectId);
        }

        if (CollectionUtils.isNotEmpty(statList)) {
            for (DataStat dataStat : statList) {
                timeList.add(dataStat.getStatDate().substring(dataStat.getStatDate().length() - 2));
                yesterdayList.add(dataStat.getSuccessCount().toString());
                historyAvgList.add(dataStat.getSuccessHistoryCount().toString());
            }
        } else {//数据为null时处理
            for (int i = 0; i < 24; i++) {
                String hour = i + "";
                if (hour.length() == 1) {
                    hour = "0" + i;
                }
                timeList.add(hour);
                yesterdayList.add("0");
                historyAvgList.add("0");
            }
        }
        yesterdayDataMap.put("name", "yesterdayList");
        yesterdayDataMap.put("data", yesterdayList);
        dataList.add(yesterdayDataMap);
        Map<String, Object> historyAvgMap = Maps.newHashMap();
        historyAvgMap.put("name", "historyAvgList");
        historyAvgMap.put("data", historyAvgList);
        dataList.add(historyAvgMap);

        //今日数据
        List<StateDto> todayStatList;
        if (StringUtils.isBlank(projectId)) {
            //项目空间id集合
            List<String> projectIdList = Lists.newArrayList();
            String userId = ThreadContextHelper.getUserId();
            if (StringUtils.isBlank(userId)) {
                userId = "1";
            }
            List<Project> list = projectService.getProjectByUserId(userId);
            for (Project project : list) {
                projectIdList.add(project.getId());
            }
            todayStatList = processInstanceService.getTodayDataAll(today, projectIdList,
                    ExecutionStatus.SUCCESS.getCode());
        } else {
            todayStatList = processInstanceService.getTodayDataByProjectId(today, projectId,
                    ExecutionStatus.SUCCESS.getCode());
        }
        String hour = DateUtils.getSystemCurrentHour();
        Map<String, Integer> successTodayMap = Maps.newHashMap();
        if (todayStatList != null && todayStatList.size() > 0) {
            for (StateDto stateDto : todayStatList) {
                successTodayMap.put(stateDto.getStatDate(), stateDto.getStatCount());
            }
            for (int i = 0; i < Integer.parseInt(hour) + 1; i++) {
                String str = String.valueOf(i);
                if (str.length() == 1) {
                    str = "0" + str;
                }
                int successCount = successTodayMap.get(today + str) == null ? 0 :
                        successTodayMap.get(today + str);
                todayList.add(String.valueOf(successCount));
            }
        } else {
            for (int i = 0; i < Integer.parseInt(hour) + 1; i++) {
                todayList.add("0");
            }
        }

        Map<String, Object> todayDataMap = Maps.newHashMap();
        todayDataMap.put("name", "todayList");
        todayDataMap.put("data", todayList);
        dataList.add(todayDataMap);

        map.put("timeList", timeList);
        map.put("dataList", dataList);
        return map;
    }

    public List<Map<String, Object>> historySuccessDataList() {
        return this.mapper.historySuccessDataList();
    }

    public List<Map<String, Object>> historyFailDataList() {
        return this.mapper.historyFailDataList();
    }

    public  List<DataStat> getDataByProjectId(String yesterday, String projectId){
        return this.mapper.getDataByProjectId(yesterday, projectId);
    }

    public void insertListByBatch(List<DataStat> subList){
        this.mapper.insertListByBatch(subList);
    }

    public void updateListByBatch(List<DataStat> subList){
        this.mapper.updateListByBatch(subList);
    }

    public boolean isRun() {
        String yesterday = DateUtils.getDayNumBeforeToday(1);
        List<DataStat> list = this.getDataByProjectId(yesterday,null);
        if(CollectionUtils.isNotEmpty(list)){
            return true;
        }
        return false;
    }
}
